package com.web.reply;

import com.bean.Remark;
import com.bean.Reply;
import com.bean.User;
import com.service.ReplyService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

public class DisplayReplyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        ReplyService service=new ReplyService();
        User user=(User)session.getAttribute("user");

        int remarkId=0;
        if(user!=null){
            try {
                String f= (String) session.getAttribute("delFlag");
                if(f!=null && f.equals("true")){
                    remarkId= (int) session.getAttribute("remarkId");
                    session.removeAttribute("delFlag");
                }else{
                    remarkId= Integer.parseInt(req.getParameter("remarkId"));
                }

                List<Reply> replies=service.getAllReply(remarkId);
                session.setAttribute("allReply",replies);

                req.getRequestDispatcher("/admin/remark/RemarkMange.jsp").forward(req,resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else{
            List<Remark> remarks= (List<Remark>) session.getAttribute("singleRemark");
            List<Reply> SingleReply= null;
            Map<Remark, List<Reply>> dataMap = new HashMap<>();
            try {
                for(Remark remark:remarks){
                     remarkId=remark.getId();
                    SingleReply = service.queryReply(remarkId);
                    dataMap.put(remark,SingleReply);
                }
                session.setAttribute("all",dataMap);

                req.getRequestDispatcher("/front/article/ArticleSingle.jsp").forward(req,resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }




    }
}
